<template>
  <label>
    <input v-if="isGroup" type="checkbox" :disabled="disabled" :value="label" v-model="model" @change="change" />
    <input v-else type="checkbox" :disabled="disabled" :checked="currentValue" @change="change" />
    <slot />
  </label>
</template>

<script>
import Emitter from '@/mixins/emitter.js'
import { findComponentUpward } from '@/utils/assist'
export default {
  name: 'gCheckbox',
  mixins: [Emitter],
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [String, Number, Boolean],
      default: false,
    },
    trueValue: {
      type: [Boolean, Number, String],
      default: true,
    },
    falseValue: {
      type: [Boolean, Number, String],
      default: false,
    },
    label: {
      type: [String, Number, Boolean],
    },
  },
  data() {
    return {
      currentValue: false,
      model: [],
      isGroup: false,
      parent: null,
    }
  },
  watch: {
    value(val) {
      if (val === this.trueValue || val === this.falseValue) {
        this.updateModel()
      } else {
        throw 'Value should be trueValue or falseValue.'
      }
    },
  },
  mounted() {
    this.parent = findComponentUpward(this, 'gCheckboxGroup')
    if (this.parent) this.isGroup = true
    if (this.isGroup) {
      this.parent.updateModel(true)
    } else {
      this.updateModel()
    }
  },
  methods: {
    updateModel() {
      this.currentValue = this.value === this.trueValue
    },
    change(event) {
      if (this.disabled) return false
      const checked = event.target.checked
      this.currentValue = checked
      const value = checked ? this.trueValue : this.falseValue
      this.$emit('input', value)
      if (this.isGroup) {
        this.parent.change(this.model)
      } else {
        this.$emit('change', value)
        this.dispatch('gFormItem', 'on-form-change', value)
      }
    },
  },
}
</script>
